const newsData = require('../data/news');

exports.getSitemap = (req, res) => {
  const baseUrl = `${req.protocol}://${req.get('host')}`;
  const routes = [
    { path: '/', changefreq: 'weekly', priority: 1.0 },
    { path: '/about', changefreq: 'monthly', priority: 0.8 },
    { path: '/news', changefreq: 'weekly', priority: 0.9 }
  ];

  // 将每条新闻也加入 sitemap
  const newsRoutes = newsData.map(item => ({
    path: `/news/${item.id}`,
    changefreq: 'monthly',
    priority: 0.7
  }));

  const allRoutes = [...routes, ...newsRoutes];

  let xml = `<?xml version="1.0" encoding="UTF-8"?>\n`;
  xml += `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n`;

  allRoutes.forEach(route => {
    xml += `  <url>\n`;
    xml += `    <loc>${baseUrl}${route.path}</loc>\n`;
    xml += `    <changefreq>${route.changefreq}</changefreq>\n`;
    xml += `    <priority>${route.priority}</priority>\n`;
    xml += `  </url>\n`;
  });

  xml += `</urlset>`;
  res.header('Content-Type', 'application/xml');
  res.send(xml);
};